﻿using DataModels.Entities.Base;
using DataModels.Entities.WorkOrder;
using DataModels.Enums.WorkOrder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Services.AuthCore;
using Services.WorkOrder;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WeChatServices;

namespace ScheduledTasks.HomeService
{
    public class WorkOrderExpires : IScheduledTask
    {
        private readonly ILogger<OrderExpires> _logger;
        private readonly WeChatMessageHandler _messageHandler;
        protected readonly OauthService _oauthService;
        protected readonly WorkOrderRapidService _WorkOrderRapidService;
        private SqlSugarClient _db;

        public WorkOrderExpires(ILogger<OrderExpires> logger, WorkOrderRapidService WorkOrderRapidService, IConfiguration configuration, OauthService oauthService)
        {
            _logger = logger;
            _messageHandler = new WeChatMessageHandler(configuration, _oauthService);
            _oauthService = oauthService;
            _WorkOrderRapidService = WorkOrderRapidService;
        }

        // 每24小时执行一次（从任务启动开始计算）
        public string Schedule => "0 0 */2 * * *";

        public async Task<Task> ExecuteAsync(SqlSugarClient db)
        {
            try
            {
                _db = db;
                await _db.BeginTranAsync();
                _logger.LogInformation("开始处理医院过期工单，时间：{DateTime}", DateTime.Now);
                var targetTime = DateTime.Now.AddHours(-23);//接近24小时通知

                // 查询待支付过期工单
                var expiredRecords = await _db.Queryable<WorkOrderRapid>() //状态小于4就使用微信模板通知
                    .Where(hso => 
                    (int)hso.Status < 4
                    && hso.Inform == 0 // 通知判断
                    && hso.CreateTime < targetTime) // 新增时间判断
                    .ToListAsync();

                _logger.LogInformation("查询到 {Count} 个医院过期工单", expiredRecords.Count);

                if (expiredRecords.Count != 0)
                {
                    if (expiredRecords.Any())
                    {
                        // 发送模板消息
                        try
                        {
                            foreach (var order in expiredRecords)
                            {
                                _WorkOrderRapidService.automaticDispatch(order);

                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "发送模板消息时发生异常");
                        }
                    }

                   // 更新工单状态为已通知
                    foreach (var order in expiredRecords)
                    {
                        order.Inform = order.Inform + 1;
                    }

                    var updateCount = await _db.Updateable(expiredRecords).ExecuteCommandAsync();
                    _logger.LogInformation("成功更新 {Count} 个医院工单状态为已通知", updateCount);

                    // 记录工单历史
                    await RecordOrderHistories(expiredRecords, "医院工单超时未处理，自动通知");
                }

                await _db.CommitTranAsync();
                _logger.LogInformation("过期医院工单处理完成，时间：{DateTime}", DateTime.Now);
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                await _db.RollbackTranAsync();
                _logger.LogError(ex, "处理待过期工单时发生错误");
                return Task.CompletedTask;
            }
        }

        public async Task RecordOrderHistories(List<WorkOrderRapid> orders, string reason)
        {
            try
            {
                var histories = orders.Select(order =>
                {
                    WorkOrderHistory history = JsonSerializer.Deserialize<WorkOrderHistory>(
                           JsonSerializer.Serialize(order)
                       );
                    history.ReasonForChange = reason;
                    return history;
                }).ToList();

                await _db.Insertable(histories).ExecuteCommandAsync();
                _logger.LogInformation("成功记录 {Count} 条工单历史", histories.Count);
            }
            catch (Exception ex)
            {
                Console.WriteLine("记录医院工单历史时发生错误");
                _logger.LogError(ex, "医院记录工单历史时发生错误");
            }
        }
    }
}
